<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-date-picker type="datetimerange"

                        :default-time="['00:00:00', '23:59:59']"
                        v-model="queryParams.myCreateTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="-" start-placeholder="创建开始日期"
                        end-placeholder="创建结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker v-model="queryParams.myAuthtime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetimerange" :default-time="['00:00:00', '23:59:59']"
                        range-separator="-" start-placeholder="实名开始日期"
                        end-placeholder="实名结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker v-model="queryParams.myActivationTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="激活开始日期"
                        end-placeholder="激活结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker v-model="queryParams.mySuccessfutime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="交易成功开始日期"
                        end-placeholder="交易成功结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-date-picker v-model="queryParams.myFailureTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="交易失败开始日期"
                        end-placeholder="交易失败结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-input style="width: 120px"
                  v-model.trim="queryParams.firstChargePriceLow"
                  placeholder="首充最小金额"
                  type="number"></el-input>
        <el-input style="width: 120px"
                  v-model.trim="queryParams.firstChargePriceUp"
                  placeholder="首充最大金额"
                  type="number"></el-input>
      </el-form-item>


      <el-form-item>
        <el-select ref="typeSelect" v-model="queryParams.types" multiple filterable reserve-keyword collapse-tags
                   placeholder="订单类型"
                   clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="typeIsAllSelect" @change="typeChange">
            全选/取消全选
          </el-checkbox>
          <el-option v-for="dict in dict.type.order_type" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select v-model="queryParams.doudianOrderShopIds" multiple filterable reserve-keyword collapse-tags
                   placeholder="订单来源"
                   clearable
                   style="width: 240px">
          <el-option v-for="item in douDianShopList" :key="item.key" :label="item.key"
                     :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="douDianGoodsSelect" v-model="queryParams.douDianGoodsNames" multiple filterable reserve-keyword
                   placeholder="抖店商品名称" collapse-tags
                   clearable style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="douDianGoodsIsAllSelect"
                       @change="douDianGoodsNamesChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="item in douDianGoodsList" :key="item.id" :label="item.title"
                     :value="item.productId"/>
        </el-select>
      </el-form-item>


      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="businessSelect" v-model="queryParams.businessIds" multiple filterable reserve-keyword
                   collapse-tags
                   placeholder="分销商户" clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="businessIdsIsAllSelect"
                       @change="businessIdsChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="item in businessList" :key="item.id" :label="item.name"
                     :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="classSelect" v-model="queryParams.classnames" multiple filterable reserve-keyword collapse-tags
                   placeholder="运营商" clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="classnamesIsAllSelect"
                       @change="classnamesChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="item in classList" :key="item.id" :label="item.title"
                     :value="item.id"/>
        </el-select>
      </el-form-item>


      <el-form-item>

        <el-select v-model="queryParams.labelTypes" multiple filterable reserve-keyword collapse-tags
                   placeholder="包含标签" clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="labelTypeIsAllSelect"
                       @change="toggleSelectAll">全选/取消全选
          </el-checkbox>
          <el-option v-for="dict in dict.type.order_label_type" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select v-model="queryParams.notLabelTypes" multiple filterable reserve-keyword collapse-tags clearable
                   placeholder="不含标签"

                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="notLabelTypeIsAllSelect"
                       @change="notToggleSelectAll">全选/取消全选
          </el-checkbox>
          <el-option v-for="dict in dict.type.order_label_type" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select ref="dDOrderStatusSelect" v-model="queryParams.doudianOrderStatuss" multiple filterable
                   reserve-keyword collapse-tags
                   placeholder="抖店订单状态" clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="doudianOrderStatusIsAllSelect"
                       @change="doudianOrderStatusChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="dict in dict.type.order_doudian_status" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-select ref="statesSelect" v-model="queryParams.states" multiple filterable reserve-keyword collapse-tags
                   placeholder="订单状态" clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="statesIsAllSelect" @change="statesChange">
            全选/取消全选
          </el-checkbox>
          <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-select v-model="queryParams.isActivations" collapse-tags
                   placeholder="是否激活" multiple
                   clearable
                   style="width: 240px">
          <el-option v-for="dict in dict.type.order_is_activation" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>


      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="receiveSelect"
                   v-model="queryParams.receiveOrderUserIds"
                   multiple filterable reserve-keyword
                   collapse-tags
                   placeholder="跟单人"
                   clearable
                   style="width: 240px"
        >
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px"
                       v-model="receiveOrderUserIdIsAllSelect"
                       @change="receiveOrderUserIdsChange"
          >全选/取消全选
          </el-checkbox>
          <!-- 动态渲染过滤后的选项 -->
          <el-option
            v-for="item in sysUserList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="maintainManageSelect" v-model="queryParams.maintainManageIds" multiple filterable
                   reserve-keyword collapse-tags
                   placeholder="维系人"
                   clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="maintainManageIdsIsAllSelect"
                       @change="maintainManageIdsChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="item in sysUserList" :key="item.userId" :label="item.nickName"
                     :value="item.userId"/>
        </el-select>
      </el-form-item>

      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="manageSelect" v-model="queryParams.manageIds" multiple filterable reserve-keyword collapse-tags
                   placeholder="实名完成人" clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="manageIdsIsAllSelect"
                       @change="manageIdsChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="item in sysUserList" :key="item.userId" :label="item.nickName"
                     :value="item.userId"/>
        </el-select>
      </el-form-item>

      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="dDOrderManageAuthorSelect" v-model="queryParams.doudianOrderManageAuthorIds" multiple filterable
                   reserve-keyword
                   collapse-tags
                   placeholder="带货主播"
                   clearable
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="doudianOrderManageAuthorIdsIsAllSelect"
                       @change="doudianOrderManageAuthorIdsChange">
            全选/取消全选
          </el-checkbox>
          <el-option v-for="item in sysUserListByGroupId16" :key="item.userId" :label="item.nickName"
                     :value="item.userId"/>
        </el-select>
      </el-form-item>

      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="dDOrderAuthorSelect" v-model="queryParams.doudianOrderAuthorIds" multiple filterable
                   reserve-keyword
                   placeholder="带货账号"
                   clearable collapse-tags
                   style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="doudianOrderAuthorIdsIsAllSelect"
                       @change="doudianOrderAuthorIdsChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="item in authorList" :key="item.uid" :label="item.name"
                     :value="item.uid"/>
        </el-select>
      </el-form-item>

      <el-form-item v-if="isOrderOptions ==1">
        <el-select ref="supplierNameSelect" v-model="queryParams.suppliernames" multiple filterable reserve-keyword
                   placeholder="号码仓" collapse-tags
                   clearable style="width: 240px">
          <el-checkbox style="margin-left: 20px;margin-bottom: 10px" v-model="suppliernamesIsAllSelect"
                       @change="suppliernamesChange">全选/取消全选
          </el-checkbox>
          <el-option v-for="item in supplierList" :key="item.id" :label="item.title"
                     :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select style="width: 240px" v-model="queryParams.channelIds" filterable collapse-tags multiple
                   reserve-keyword collapse-tags
                   placeholder="发展渠道" clearable>
          <el-option v-for="item in orderChannelList" :key="item.id" :label="item.channelName"
                     :value="item.id"/>
        </el-select>
      </el-form-item>

      <!--      <el-form-item>-->
      <!--        <el-select style="width: 240px" v-model="queryParams.evidenceChainTags" filterable collapse-tags multiple-->
      <!--                   reserve-keyword collapse-tags-->
      <!--                   placeholder="证据链" clearable>-->
      <!--          <el-option label="完整" value="1"/>-->
      <!--          <el-option label="缺失" value="0"/>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->


      <el-tabs v-model="tabPaneValue" @tab-click="handleClick">
        <el-tab-pane label="订单搜索" name="first">
          <el-form-item prop="synthesize">
            <el-input style="width: 450px"
                      title="订单号码/订单编号/客户姓名/联系电话/联系地址/抖店编号/身份证号"
                      v-model.trim="queryParams.synthesize"
                      placeholder="订单号码/订单编号/客户姓名/联系电话/联系地址/抖店编号/身份证号"
                      clearable
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="描述搜索" name="second">
          <el-form-item prop="orderFollowContent">
            <el-input style="width: 400px"
                      v-model.trim="queryParams.orderFollowContent"
                      placeholder="描述搜索"
                      clearable
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="多订单号码搜索" name="third">
          <el-form-item prop="telNumbers">
            <el-input style="width: 400px"
                      v-model.trim="queryParams.telNumbers"
                      clearable
                      type="textarea" placeholder="请输入订单号码,每个号码必须换行"></el-input>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="多订单编号搜索" name="fourth">
          <el-form-item prop="serials">
            <el-input style="width: 400px"
                      v-model.trim="queryParams.serials"
                      clearable
                      type="textarea" placeholder="请输入订单编号,每个号码必须换行"></el-input>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="多抖店编号搜索" name="fifth">
          <el-form-item prop="douDianIds">
            <el-input style="width: 400px"
                      v-model.trim="queryParams.douDianIds"
                      clearable
                      type="textarea" placeholder="请输入抖店编号,每个号码必须换行"></el-input>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <span style="margin-left: 10px">库内符合查询条件的有<span style="color: #409EFF">{{ total }}</span>个,请选择操作!</span>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hmk:order:export']"
        >导出
        </el-button>

        <el-button
          type="primary"
          size="mini"
          @click="addGenJinClick">批量跟进
        </el-button>

        <el-button
          type="primary"
          size="mini"
          @click="batchUpdatePricePre">批量改价
        </el-button>


        <el-button size="mini" type="primary" @click="businessSuccessClick()">
          批量竣工
        </el-button>

      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange"
              :row-class-name="setHighlightRow" @row-click="handleRowClick">
      <el-table-column type="selection" width="50" align="left"/>
      <el-table-column label="订单号码" align="left" prop="telNumber" width="110"/>
      <el-table-column label="用户姓名" align="left" prop="customName" width="80"/>
      <el-table-column label="号码仓" align="left" prop="title" width="220px">
        <template #default="{row}">
          {{ row.showRealTitle ? row.title : (row.title ? '******' : '') }}
          <i v-if="row.title" class="el-icon-view other-icon" @click.stop="toggleRealTitle(row)"/>
        </template>
      </el-table-column>
      <el-table-column label="分销商户" align="left" prop="businessName" width="80"/>
      <el-table-column label="跟单人" align="left" prop="receiveOrderUserId" width="100"/>
      <el-table-column label="维系人" aalign="left" prop="trueName" min-width width="100"/>

      <el-table-column label="下单时间" sortable align="left" prop="time" width="140">
        <template slot-scope="scope">
          <span :title="formatTimeTitle(scope.row.time)">
            {{ formatTime(scope.row.time) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="外部状态" align="left" prop="douDianStatus" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dou_dian_status" :value="scope.row.douDianStatus"
          />
        </template>
      </el-table-column>

      <el-table-column label="状态" align="left" prop="state" width="180">
        <template #default="{row}">
          <el-tag title="点击查看订单详情" @click.native="toDetail(row) " size="mini"
                  style="font-size: 12px;color:#FFFFFF; cursor: pointer"
                  :color="getTagClass(row.state) ">
            {{ orderState(row.state) }}
          </el-tag>

          <el-tag
            title="点击查看订单详情"
            v-if="row.otherTag && row.otherTag.length > 0"
            @click.native="toDetail(row) " size="mini" style="font-size: 12px;color:#FFFFFF; cursor: pointer"
            :color="getTagClass(row.state) ">
            {{ row.otherTag.join(",") }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="描述" align="left" prop="state">
        <template #default="{row}">
          <div style="display: flex; justify-content: flex-start;align-items: center">
            <el-tag @click.native="toOrderFollow(row) "
                    :title="row.content"
                    style="margin:1px;font-size: 12px;color:#FFFFFF;width: 270px;cursor: pointer"
                    size="mini"
                    :color="getTagClass(row.state)"
            >
              <i title="点击查看订单跟进" class="el-icon-edit-outline"></i> {{ formatTime2(row.followTime) }}
              {{ filterContent(row) }}
            </el-tag>
            <div>
              <el-tag :title="label.node"
                      style="margin:1px;font-size: 12px;color:#FFFFFF"
                      v-for="label in row.labelObjs"
                      :key="label.name"
                      size="mini"
                      :color="getTagClass(row.state,label.name)">
                {{ label.name }}
              </el-tag>
            </div>
          </div>
          <span>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改订单对话框 -->
    <order_follow :rowId="rowId"></order_follow>

    <el-dialog title="添加跟进" :visible.sync="addGenJinVisible" width="800px" :before-close="addGenJinClose">
      <el-form :model="addGenJinForm" label-width="120px" ref="addGenJinForm" @submit.native.prevent="enterSubmit">

        <el-form-item label="紧急状态">
          <el-radio v-model="addGenJinForm.emergentStatus" label="1">正常</el-radio>
          <el-radio v-model="addGenJinForm.emergentStatus" label="2">紧急</el-radio>
        </el-form-item>

        <el-form-item label="展现对象">
          <el-checkbox-group v-model="addGenJinForm.displayObjects">
            <el-checkbox label="2">会员端</el-checkbox>
            <el-checkbox label="3">供应商</el-checkbox>
            <el-checkbox label="4">分销商</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="跟进内容" prop="defineLabelNotes">
          <el-input type="textarea" v-model="addGenJinForm.defineLabelNotes"
                    placeholder="请输入跟进内容(必填)"></el-input>
        </el-form-item>

        <el-form-item label="定义标签">
          <el-input v-model="addGenJinForm.defineLabel"
                    placeholder="非必填,若需使用请输入6字内的定义标签,标签将在列表展示"></el-input>
        </el-form-item>

        <el-form-item label="失效节点">
          <el-select style="width: 100%" v-model="addGenJinForm.defineLabelStatus" filterable collapse-tags
                     placeholder="请选择以上定义标签在哪个环节失效" clearable>
            <el-option v-for="item in defineLabelStatusData" :key="item.key" :label="item.value" :value="item.key"/>
          </el-select>
        </el-form-item>
        <div class="hjfBottomFoot">
          <el-button size="small" @click="addGenJinClose" style="margin-right: 1px">取 消</el-button>
          <el-button size="small" type="primary" @click="batchAddGenJinFormConfirm('addGenJinForm')">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog :title="'对'+ids.length+'个订单执行批量改价'" :visible.sync="batchUpdatePriceVisible" width="600px">
      <el-form
        :model="batchUpdatePriceForm"
        label-width="80px"
        @submit.native.prevent="batchUpdatePriceFormConfirm">

        <el-form-item label="订单价格">
          <el-input type="number" v-model="batchUpdatePriceForm.orderprice"></el-input>
        </el-form-item>

        <el-form-item label="结算价">
          <el-input type="number" v-model="batchUpdatePriceForm.settlementprice"></el-input>
        </el-form-item>

        <el-form-item label="上传底价">
          <el-input type="number" v-model="batchUpdatePriceForm.uploadfloorprice"></el-input>
        </el-form-item>

        <div style="color: #c2c4d4">
          <span style=" margin-left: 20px"> 商户利润:{{ batchUpdatePriceForm.businessProfit }}</span>
          <span style=" margin-left: 40px"> 平台利润:{{ batchUpdatePriceForm.platformProfit }} </span>
        </div>

        <div class="hjfBottomFoot">
          <el-button size="small" @click="batchUpdatePriceVisible = false">取 消</el-button>
          <el-button size="small"
                     type="primary"
                     @click="batchUpdatePriceFormConfirm">
            确 定
          </el-button>
        </div>
      </el-form>
    </el-dialog>


    <el-dialog :title="'对'+ids.length+'个订单执行批量竣工'" :visible.sync="form_businessSuccessVisible" width="36%"
               v-loading="loading">
      <el-form :model="form_businessSuccess" label-width="170px">

        <el-form-item label="给佣类型">
          <el-radio-group v-model="form_businessSuccess.commissionpriceType">
            <el-radio :label="1">即返佣金</el-radio>
            <el-radio :label="2">后返佣金</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="[68]胡权给佣比例%" v-show="form_businessSuccess.commissionpriceType == 2">
          <el-input type="number" v-model="form_businessSuccess.fuQuan" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="[7]抖音周健给佣比例%" v-show="form_businessSuccess.commissionpriceType == 2">
          <el-input type="number" v-model="form_businessSuccess.zhouJian"
                    style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="[167]抖音李洪给佣比例%" v-show="form_businessSuccess.commissionpriceType == 2">
          <el-input type="number" v-model="form_businessSuccess.liHong" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="给佣金额" v-show="form_businessSuccess.commissionpriceType != 2">
          <el-input type="number" v-model="form_businessSuccess.commissionprice"
                    placeholder="请输入给佣金额" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="已完工备注">
          <el-input style="width: 400px" type="textarea" v-model="form_businessSuccess.content"
                    placeholder="请输入已完工备注"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="form_businessSuccessVisible = false">取 消</el-button>
        <el-button type="primary" @click="form_businessSuccessConfirm">确 定</el-button>
      </div>

    </el-dialog>

  </div>
</template>
<script>
import {
  addOrder,
  batchAddGenJin,
  batchUpdatePrice,
  batchUpdateState6,
  delOrder,
  douDianGoodsList,
  getIdentityVisible,
  getOrder,
  getSupplierTitle,
  listOrder,
  orderChannelSimpleList,
  updateOrder,
} from "@/api/hmk/order";
import {simpleClassList} from "@/api/order/class"
import {
  getCurrentUserInfo,
  getReceiveOrderUserSimpleUserList,
  getSimpleUserList,
  getSimpleUserListByGroupId16
} from "@/api/system/user"
import {getBusinessSimple} from "@/api/hmk/business"
import {simpleList} from "@/api/hmk/author"
import {listByIsProtective} from "@/api/hmk/supplier"
import Order_follow from "@/views/hmk/order/order_follow.vue";
import {
  formatTime,
  formatTime2,
  formatTimeTitle,
  formatTimeTitleExcel,
  getStateClass,
  getTagClass,
  orderState
} from "@/utils/hjf-common";

export default {
  async concurrentReq(requests) {
    const results = await Promise.allSettled(requests);
    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        console.log(`请求 ${index} 成功:`, result.value);
      } else {
        console.error(`请求 ${index} 失败:`, result.reason);
      }
    });
    return results;
  },
  name: "Order",
  components: {Order_follow},
  dicts: ['sys_normal_disable', 'order_status', 'dou_dian_status', 'order_label_type', 'order_type', 'order_is_activation', 'order_doudian_status'],
  data() {
    return {
      labelPosition: 'left',
      form_businessSuccess: {
        commissionpriceType: null,
        commissionprice: null,
        businessId: null,
        commissionpriceArr: null,
        content: null,
        liHong: null,
        zhouJian: null,
        fuQuan: null,
      },
      form_businessSuccessVisible: false,
      batchUpdatePriceForm: {
        orderprice: null,
        settlementprice: null,
        uploadfloorprice: null,
        businessProfit: null,
        platformProfit: null
      },
      batchUpdatePriceVisible: false,
      douDianGoodsList: [],
      orderChannelList: [],
      defineLabelStatusData: [
        {key: '3', value: '处理中'},
        {key: '5', value: '已实名'},
        {key: '6', value: '已完成'}],
      addGenJinForm: {
        emergentStatus: '1',
        defineLabel: '',
        defineLabelStatus: '',
        defineLabelNotes: '',
        displayObjects: ['4']
      },
      addGenJinVisible: false,
      receiveOrderUserList: [],
      douDianShopList: [
        {key: '联通专卖店', value: '104110047'},
        {key: '数码大超市', value: '175974257'},
        {key: '町町科技', value: '142993946'}],
      selectedRowId: null,
      isOrderOptions: 2,
      rowId: null,
      deadline4: Date.now() + (new Date().setHours(40, 59, 59) - Date.now()),
      tabPaneValue: "first",
      filterText: "", // 过滤输入框的值
      isCollapseTags: true,
      labelTypeIsAllSelect: false,
      notLabelTypeIsAllSelect: false,
      typeIsAllSelect: false,
      statesIsAllSelect: false,
      doudianOrderStatusIsAllSelect: false,
      classnamesIsAllSelect: false,
      businessIdsIsAllSelect: false,
      receiveOrderUserIdIsAllSelect: false,
      maintainManageIdsIsAllSelect: false,
      manageIdsIsAllSelect: false,
      doudianOrderManageAuthorIdsIsAllSelect: false,
      doudianOrderAuthorIdsIsAllSelect: false,
      suppliernamesIsAllSelect: false,
      douDianGoodsIsAllSelect: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      classList: [],
      sysUserList: [],
      businessList: [],
      authorList: [],
      sysUserListByGroupId16: [],
      supplierList: [],
      // 查询参数
      queryParams: {
        evidenceChainTags: [],
        douDianGoodsNames: [],
        channelIds: [],
        pageNum: 1,
        pageSize: 10,
        telNumber: null,
        myCreateTime: [],
        myAuthtime: [],
        myActivationTime: [],
        mySuccessfutime: [],
        myFailureTime: [],
        firstChargePriceLow: null,
        firstChargePriceUp: null,
        labelTypes: [],
        notLabelTypes: [],
        types: [],
        states: [],
        doudianOrderStatuss: [],
        classnames: [],
        businessIds: [],
        receiveOrderUserIds: [],
        maintainManageIds: [],
        doudianOrderAuthorIds: [],
        doudianOrderManageAuthorIds: [],
        manageIds: [],
        suppliernames: [],
        serial: null,
        synthesize: null,
        queryType: null,
        orderFollowContent: null,
        telNumbers: null,
        serials: null,
        douDianIds: null,
        doudianOrderShopIds: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  computed: {
    currentUser() {
      return this.$store.state.user.id;
    },

  },
  watch: {
    'form_businessSuccess.commissionpriceType'(newVal) {
      if (newVal == 2) {
        this.form_businessSuccess.fuQuan = 15;
        this.form_businessSuccess.zhouJian = 15;
        this.form_businessSuccess.liHong = 20;
        this.form_businessSuccess.content = null;
      }
    },
    'batchUpdatePriceForm.orderprice'(newVal) {
      if (newVal) {
        if (this.batchUpdatePriceForm.settlementprice) {
          this.batchUpdatePriceForm.businessProfit = parseFloat(this.batchUpdatePriceForm.orderprice - this.batchUpdatePriceForm.settlementprice).toFixed(2);
        }
      } else {
        this.batchUpdatePriceForm.businessProfit = null;
      }
    },

    'batchUpdatePriceForm.settlementprice'(newVal) {
      if (newVal) {
        if (this.batchUpdatePriceForm.orderprice) {
          this.batchUpdatePriceForm.businessProfit = parseFloat(this.batchUpdatePriceForm.orderprice - this.batchUpdatePriceForm.settlementprice).toFixed(2);
        }
        if (this.batchUpdatePriceForm.uploadfloorprice) {
          this.batchUpdatePriceForm.platformProfit = parseFloat(this.batchUpdatePriceForm.settlementprice - this.batchUpdatePriceForm.uploadfloorprice).toFixed(2);
        }
      } else {
        this.batchUpdatePriceForm.businessProfit = null;
        this.batchUpdatePriceForm.platformProfit = null;
      }
    },

    'batchUpdatePriceForm.uploadfloorprice'(newVal) {
      if (newVal) {
        if (this.batchUpdatePriceForm.settlementprice) {
          this.batchUpdatePriceForm.platformProfit = parseFloat(this.batchUpdatePriceForm.settlementprice - this.batchUpdatePriceForm.uploadfloorprice).toFixed(2);
        }
      } else {
        this.batchUpdatePriceForm.platformProfit = null;
      }
    },

    'queryParams.synthesize'(newVal) {
      if (newVal) {
        this.queryParams.synthesize = newVal.replace(/\s+/g, '');
      }
    },
    'queryParams.telNumbers'(newVal) {
      if (newVal) {
        this.queryParams.telNumbers = newVal.replace(/[^\S\n\r]+/g, '');
      }
    },
    'queryParams.serials'(newVal) {
      if (newVal) {
        this.queryParams.serials = newVal.replace(/[^\S\n\r]+/g, '');
      }
    },
    'queryParams.douDianIds'(newVal) {
      if (newVal) {
        this.queryParams.douDianIds = newVal.replace(/[^\S\n\r]+/g, '');
      }
    },
    'addGenJinForm.defineLabel'(newVal) {
      if (newVal.toString().length > 6) {
        this.addGenJinForm.defineLabel = newVal.toString().slice(0, 6)
      }
    },
    '$store.state.orderFollow.orderDetailFlushTag'(newVal) {
      if (newVal) {
        this.$store.commit('SET_ORDER_DETAIL_FLUSH_TAG_FALSE');
        this.getList()
      }
    },
  },
  async mounted() {
    try {
      if (!this.currentUser) {
        this.$modal.msgError("未获取到用户信息");
        return;
      }
      const userInfo = await getCurrentUserInfo(this.currentUser);
      this.isOrderOptions = userInfo.data.isOrderOptions;
      const results = await Promise.allSettled([
        this.getList(),
        this.getClassList(),
        this.getManageListSimple(),
        this.getBusinessListSimple(),
        this.getAuthorList(),
        this.getSimpleUserListByGroupId16(),
        this.getSupplierList(),
        this.getReceiveOrderUserSimpleUserList(),
        this.orderChannelSimpleList(),
        this.selectDouDianGoodsList(),
      ]);
      results.forEach((result, index) => {
        if (result.status === 'fulfilled') {

        } else {

        }
      });

    } catch (error) {
      console.log(error.message);
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getList() // 进入路由时调用方法
    })
  },

  methods: {
    async form_businessSuccessConfirm() {
      let query = {ids: this.ids, commissionpriceType: this.form_businessSuccess.commissionpriceType};
      if (this.form_businessSuccess.commissionpriceType == 1) {
        if (this.form_businessSuccess.commissionprice == null || this.form_businessSuccess.commissionprice == '' || this.form_businessSuccess.commissionprice < 0) {
          this.$modal.msgError("即返佣金必填且大于或等于0")
          return;
        } else {
          query.commissionprice = this.form_businessSuccess.commissionprice;
        }
      }
      if (this.form_businessSuccess.commissionpriceType == 2) {
        if ((this.form_businessSuccess.fuQuan == null || this.form_businessSuccess.fuQuan == '') &&
          (this.form_businessSuccess.zhouJian == null || this.form_businessSuccess.zhouJian == '') &&
          (this.form_businessSuccess.liHong == null || this.form_businessSuccess.liHong == '')) {
          this.$modal.msgError("后返佣金值必填一个且大于0")
          return;
        }
      }
      if (this.form_businessSuccess.commissionpriceType == 2) {
        if (this.form_businessSuccess.fuQuan != '' && this.form_businessSuccess.fuQuan <= 0) {
          this.$modal.msgError("后返佣金额胡权必填一个且大于0")
          return;
        }
        if (this.form_businessSuccess.zhouJian != '' && this.form_businessSuccess.zhouJian <= 0) {
          this.$modal.msgError("后返佣金额周健必填一个且大于0")
          return;
        }
        if (this.form_businessSuccess.liHong != '' && this.form_businessSuccess.liHong <= 0) {
          this.$modal.msgError("后返佣金额李洪必填一个且大于0")
          return;
        }
      }
      query.commissionPriceArr = [];
      let sum = 0;
      if (this.form_businessSuccess.commissionpriceType == 2) {
        if (this.form_businessSuccess.fuQuan > 0) {
          sum = Number(sum) + Number(this.form_businessSuccess.fuQuan);
          query.commissionPriceArr.push({
            'id': 68,
            'name': '【68】胡权',
            'lv': this.form_businessSuccess.fuQuan
          })
        }
        if (this.form_businessSuccess.zhouJian > 0) {
          sum = Number(sum) + Number(this.form_businessSuccess.zhouJian);
          query.commissionPriceArr.push({
            'id': 7,
            'name': '【7】抖音周健',
            'lv': this.form_businessSuccess.zhouJian
          })
        }
        if (this.form_businessSuccess.liHong > 0) {
          sum = Number(sum) + Number(this.form_businessSuccess.liHong);
          query.commissionPriceArr.push({
            'id': 167,
            'name': '【167】抖音李洪',
            'lv': this.form_businessSuccess.liHong
          })
        }
        if (sum > 60) {

          this.$modal.msgError("后返佣金额总值不能大于60%")
          return;
        }
      }
      query.content = this.form_businessSuccess.content;
      this.loading = true;
      await batchUpdateState6(query).then(res => {
        this.$modal.msgSuccess(res.msg)
      })
      const res = await this.getList();
      this.loading = false;
      this.form_businessSuccessVisible = false;
    },

    businessSuccessClick() {
      if (this.ids.length == 0) {
        this.$modal.msgError('请先勾选订单!');
        return;
      }
      this.form_businessSuccessVisible = true;
      this.form_businessSuccess.commissionprice = null;
      this.form_businessSuccess.commissionpriceType = 1;
      this.form_businessSuccess.content = null;
      this.form_businessSuccess.fuQuan = null;
      this.form_businessSuccess.zhouJian = null;
      this.form_businessSuccess.liHong = null;
    },
    orderChannelSimpleList() {
      orderChannelSimpleList().then(res => {
        this.orderChannelList = res.data;
      })
    },
    selectDouDianGoodsList() {
      douDianGoodsList().then(res => {
        this.douDianGoodsList = res.data;
      })
    },
    async batchUpdatePriceFormConfirm() {
      if ((this.batchUpdatePriceForm.settlementprice === null || this.batchUpdatePriceForm.settlementprice === undefined || this.batchUpdatePriceForm.settlementprice === '') &&
        (this.batchUpdatePriceForm.uploadfloorprice === null || this.batchUpdatePriceForm.uploadfloorprice === undefined || this.batchUpdatePriceForm.uploadfloorprice === '') &&
        (this.batchUpdatePriceForm.orderprice === null || this.batchUpdatePriceForm.orderprice === undefined || this.batchUpdatePriceForm.orderprice === '')) {
        this.$modal.msgError("请至少填入一个需要修改的价格!");
        return;
      }

      this.$confirm('你确定要修改价格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const query = {
          ids: this.ids,
          ...this.batchUpdatePriceForm,
        };
        batchUpdatePrice(query).then(res => {
          this.$message({type: 'success', duration: '5000', message: res.msg});
          this.batchUpdatePriceVisible = false;
        })
      }).catch((error) => {
        this.$message({type: 'info', message: '已取消'});
      });
    },
    async batchAddGenJinFormConfirm(formName) {
      try {
        if (this.addGenJinForm.defineLabelNotes == '') {
          this.$modal.msgError('跟进内容必填');
          return false;
        }
        if ('' != this.addGenJinForm.defineLabel && this.addGenJinForm.defineLabelStatus == '') {
          this.$modal.msgError('请选择定义标签失效节点!');
          return;
        }

        if ('' == this.addGenJinForm.defineLabel && this.addGenJinForm.defineLabelStatus != '') {
          this.$modal.msgError('定义标签必须有值');
          return;
        }
        const query = {
          ids: this.ids,
          ...this.addGenJinForm,
        };
        query.labelType = null;
        await batchAddGenJin(query);
        await this.getList();
        this.$modal.msgSuccess('提交成功!');
        this.addGenJinVisible = false;
        return;
      } catch (error) {
        this.$modal.msgError('提交失败，请重试！');
      }
    },

    addGenJinClose() {
      this.addGenJinForm.defineLabel = '';
      this.addGenJinForm.defineLabelStatus = '';
      this.addGenJinForm.defineLabelNotes = '';
      this.addGenJinForm.emergentStatus = '1';
      this.addGenJinForm.displayObjects = ['4'];
      this.addGenJinVisible = false;
    },


    addGenJinClick() {
      if (this.ids.length == 0) {
        this.$modal.msgError('请先勾选订单!');
        return;
      }
      this.addGenJinForm.defineLabel = '';
      this.addGenJinForm.defineLabelStatus = '';
      this.addGenJinForm.defineLabelNotes = '';
      this.addGenJinForm.emergentStatus = '1';
      this.addGenJinForm.displayObjects = ['4'];
      this.addGenJinVisible = true;
    },

    batchUpdatePricePre() {
      if (this.ids.length == 0) {
        this.$modal.msgError('请先勾选订单!');
        return;
      }
      this.batchUpdatePriceForm.orderprice = null;
      this.batchUpdatePriceVisible = true;
      this.batchUpdatePriceForm.businessProfit = null;
      this.batchUpdatePriceForm.platformProfit = null;
      this.batchUpdatePriceForm.settlementprice = null;
      this.batchUpdatePriceForm.uploadfloorprice = null;
    },
    async toggleRealTitle(row) {
      if (row.title.length > 4) {
        return;
      }
      row.showRealTitle = !row.showRealTitle;
      const supplier = await getSupplierTitle(row);
      this.$set(row, 'title', supplier.data.title);
    },
    getIdentityVisible,
    orderState,
    getStateClass,
    getTagClass,
    formatTime,
    formatTime2,
    formatTimeTitle,
    filterContent(row) {
      if (row) {
        return row.content ? (row.content.length > 14 ? row.content.substring(0, 14) + '..' : row.content) : ''
      }
    },
    // 行点击事件
    handleRowClick(row) {
      this.selectedRowId = row.id // 保存选中行ID
      localStorage.setItem('selectedOrderId', row.id) // 持久化存储
    },
    // 设置行类名
    setHighlightRow({row}) {
      const isHighlight = row.id == this.selectedRowId;

      return {
        'highlight-row': isHighlight
      };
    },

    // 获取数据后恢复选中状态
    fetchData() {
      this.loading = true
      getOrderList().then(res => {
        this.orderList = res.data
        // 从存储中恢复选中状态
        const savedId = localStorage.getItem('selectedOrderId')
        if (savedId) {
          this.selectedRowId = savedId
        }
      }).finally(() => {
        this.loading = false
      })
    },

    otherTag(row) {

      if (row.length > 0) {
        return row.otherTag;
      }
    },
    hilarity() {
      this.$notify({
        title: "提示",
        message: "时间已到",
        duration: 0,
      });
    },
    handleClick(tab) {
      if (tab.index == 0) {

        this.queryParams.orderFollowContent = '';
        this.queryParams.telNumbers = '';
        this.queryParams.serials = '';
        this.queryParams.douDianIds = '';
      } else if (tab.index == 1) {

        this.queryParams.synthesize = '';
        this.queryParams.telNumbers = '';
        this.queryParams.serials = '';
        this.queryParams.douDianIds = '';
      } else if (tab.index == 2) {

        this.queryParams.synthesize = '';
        this.queryParams.orderFollowContent = '';
        this.queryParams.serials = '';
        this.queryParams.douDianIds = '';
      } else if (tab.index == 3) {

        this.queryParams.synthesize = '';
        this.queryParams.telNumbers = '';
        this.queryParams.orderFollowContent = '';
        this.queryParams.douDianIds = '';
      } else if (tab.index == 4) {

        this.queryParams.synthesize = '';
        this.queryParams.orderFollowContent = '';
        this.queryParams.telNumbers = '';
        this.queryParams.serials = '';
      }
    },

    //去订单详情页
    toDetail(event) {
      const query = {
        "id": event.id
      }
      this.$router.push({path: "/hmk/order/detail", query: query});
    },
    toOrderFollow(event) {
      this.$store.commit('SET_orderFollowVisible');
      this.rowId = event.id;
    },
    toggleSelectAll() {
      if (this.labelTypeIsAllSelect) {
        this.queryParams.labelTypes = this.dict.type.order_label_type.map(dict => dict.value);
      } else {
        this.queryParams.labelTypes = [];
      }
    },
    notToggleSelectAll() {
      if (this.notLabelTypeIsAllSelect) {
        this.queryParams.notLabelTypes = this.dict.type.order_label_type.map(dict => dict.value);
      } else {
        this.queryParams.notLabelTypes = [];
      }
    },
    typeChange() {
      if (this.typeIsAllSelect) {
        const filteredOptions = this.$refs.typeSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.types = filteredOptions.length > 0 ? filteredOptions : this.queryParams.types.map(dict => dict.value);
        if (filteredOptions.length > 0) {
          this.queryParams.types = [
            ...this.queryParams.types.filter(item => filteredOptions.includes(item.value)),
            ...this.queryParams.types.filter(item => !filteredOptions.includes(item.value))
          ];
        }
      } else {
        this.queryParams.types = [];
      }
    },
    statesChange() {
      if (this.statesIsAllSelect) {
        const filteredOptions = this.$refs.statesSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.states = filteredOptions.length > 0 ? filteredOptions : this.dict.type.order_status.map(dict => dict.value);
        if (filteredOptions.length > 0) {
          this.dict.type.order_status = [
            ...this.dict.type.order_status.filter(item => filteredOptions.includes(item.value)),
            ...this.dict.type.order_status.filter(item => !filteredOptions.includes(item.value))
          ];
        }
      } else {
        this.queryParams.states = [];
      }
    },

    doudianOrderStatusChange() {
      if (this.doudianOrderStatusIsAllSelect) {
        const filteredOptions = this.$refs.dDOrderStatusSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.doudianOrderStatuss = filteredOptions.length > 0 ? filteredOptions : this.dict.type.order_doudian_status.map(dict => dict.value);
        if (filteredOptions.length > 0) {
          this.dict.type.order_doudian_status = [
            ...this.dict.type.order_doudian_status.filter(item => filteredOptions.includes(item.value)),
            ...this.dict.type.order_doudian_status.filter(item => !filteredOptions.includes(item.value))
          ];
        }
      } else {
        this.queryParams.doudianOrderStatuss = [];
      }
    },
    classnamesChange() {
      if (this.classnamesIsAllSelect) {
        const filteredOptions = this.$refs.classSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.classnames = filteredOptions.length > 0 ? filteredOptions : this.classList.map(dict => dict.id);
        if (filteredOptions.length > 0) {
          this.classList = [
            ...this.classList.filter(item => filteredOptions.includes(item.id)),
            ...this.classList.filter(item => !filteredOptions.includes(item.id))
          ];
        }
      } else {
        this.queryParams.classnames = [];
      }
    },

    businessIdsChange() {
      if (this.businessIdsIsAllSelect) {
        const filteredOptions = this.$refs.businessSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.businessIds = filteredOptions.length > 0 ? filteredOptions : this.businessList.map(dict => dict.id);
        if (filteredOptions.length > 0) {
          this.businessList = [
            ...this.businessList.filter(item => filteredOptions.includes(item.id)),
            ...this.businessList.filter(item => !filteredOptions.includes(item.id))
          ];
        }
      } else {
        this.queryParams.businessIds = [];
      }
    },

    receiveOrderUserIdsChange() {
      if (this.receiveOrderUserIdIsAllSelect) {
        const filteredOptions = this.$refs.receiveSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.receiveOrderUserIds = filteredOptions.length > 0 ? filteredOptions : this.sysUserList.map(dict => dict.userId);
        if (filteredOptions.length > 0) {
          this.sysUserList = [
            ...this.sysUserList.filter(item => filteredOptions.includes(item.userId)),
            ...this.sysUserList.filter(item => !filteredOptions.includes(item.userId))
          ];
        }
      } else {
        this.queryParams.receiveOrderUserIds = [];
      }
    },
    maintainManageIdsChange() {
      if (this.maintainManageIdsIsAllSelect) {
        const filteredOptions = this.$refs.maintainManageSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.maintainManageIds = filteredOptions.length > 0 ? filteredOptions : this.sysUserList.map(dict => dict.userId);
        if (filteredOptions.length > 0) {
          this.sysUserList = [
            ...this.sysUserList.filter(item => filteredOptions.includes(item.userId)),
            ...this.sysUserList.filter(item => !filteredOptions.includes(item.userId))
          ];
        }
      } else {
        this.queryParams.maintainManageIds = [];
      }
    },

    manageIdsChange() {
      if (this.manageIdsIsAllSelect) {
        const filteredOptions = this.$refs.manageSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.manageIds = filteredOptions.length > 0 ? filteredOptions : this.sysUserList.map(dict => dict.userId);
        if (filteredOptions.length > 0) {
          this.sysUserList = [
            ...this.sysUserList.filter(item => filteredOptions.includes(item.userId)),
            ...this.sysUserList.filter(item => !filteredOptions.includes(item.userId))
          ];
        }
      } else {
        this.queryParams.manageIds = [];
      }
    },
    doudianOrderManageAuthorIdsChange() {
      if (this.doudianOrderManageAuthorIdsIsAllSelect) {
        const filteredOptions = this.$refs.dDOrderManageAuthorSelect.options.filter(option => option.visible && option.value != 202).map(option => option.value);
        this.queryParams.doudianOrderManageAuthorIds = filteredOptions.length > 0 ? filteredOptions : this.sysUserListByGroupId16
          .filter(user => user.userId != 202).map(dict => dict.userId);

        if (filteredOptions.length > 0) {
          this.sysUserListByGroupId16 = [
            ...this.sysUserListByGroupId16.filter(item => filteredOptions.includes(item.userId)),
            ...this.sysUserListByGroupId16.filter(item => !filteredOptions.includes(item.userId))
          ];
        }
      } else {
        this.queryParams.doudianOrderManageAuthorIds = [];
      }
    },
    doudianOrderAuthorIdsChange() {
      if (this.doudianOrderAuthorIdsIsAllSelect) {
        const filteredOptions = this.$refs.dDOrderAuthorSelect.options.filter(option => option.visible && option.value != 100).map(option => option.value);
        this.queryParams.doudianOrderAuthorIds = filteredOptions.length > 0 ? filteredOptions : this.authorList.filter(i => i.uid != 100).map(dict => dict.uid);
        if (filteredOptions.length > 0) {
          this.authorList = [
            ...this.authorList.filter(item => filteredOptions.includes(item.uid)),
            ...this.authorList.filter(item => !filteredOptions.includes(item.uid))
          ];
        }
      } else {
        this.queryParams.doudianOrderAuthorIds = [];
      }
    },

    suppliernamesChange() {
      if (this.suppliernamesIsAllSelect) {
        const visibleOptions = this.$refs.supplierNameSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.suppliernames = visibleOptions.length > 0 ? visibleOptions : this.supplierList.map(item => item.id);
        if (visibleOptions.length > 0) {
          this.supplierList = [
            ...this.supplierList.filter(item => visibleOptions.includes(item.id)),
            ...this.supplierList.filter(item => !visibleOptions.includes(item.id))
          ];
        }
      } else {
        this.queryParams.suppliernames = [];
      }
    },
    douDianGoodsNamesChange() {
      if (this.douDianGoodsIsAllSelect) {
        const visibleOptions = this.$refs.douDianGoodsSelect.options.filter(option => option.visible).map(option => option.value);
        this.queryParams.douDianGoodsNames = visibleOptions.length > 0 ? visibleOptions : this.douDianGoodsList.map(item => item.id);
        if (visibleOptions.length > 0) {
          this.douDianGoodsList = [
            ...this.douDianGoodsList.filter(item => visibleOptions.includes(item.id)),
            ...this.douDianGoodsList.filter(item => !visibleOptions.includes(item.id))
          ];
        }
      } else {
        this.queryParams.douDianGoodsNames = [];
      }
    },


    handleInput(index) {
      // 确保输入的值在合理范围内
      this.queryParams.myFirstChargePrice[index] = Math.max(0, Math.min(10000, this.queryParams.myFirstChargePrice[index]));
      this.$forceUpdate(); // 强制更新视图
    },

    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        const savedId = localStorage.getItem('selectedOrderId')
        if (savedId) {
          this.selectedRowId = savedId
        }
        this.loading = false;
      });
    },

    getClassList() {
      this.loading = true;
      simpleClassList().then(response => {
        this.classList = response.data;
        this.loading = false;
      });
    },
    getManageListSimple() {
      this.loading = true;
      getSimpleUserList().then(response => {
        this.sysUserList = response.data;
        this.loading = false;
        sessionStorage.setItem('sysUserList', JSON.stringify(this.sysUserList));
      });
    },
    getReceiveOrderUserSimpleUserList() {
      this.loading = true;
      getReceiveOrderUserSimpleUserList().then(response => {
        this.receiveOrderUserList = response.data;
        this.loading = false;
        sessionStorage.setItem('receiveOrderUserList', JSON.stringify(this.receiveOrderUserList));
      });
    },
    getBusinessListSimple() {
      this.loading = true;
      getBusinessSimple().then(response => {
        this.businessList = response.data;
        this.loading = false;
        sessionStorage.setItem("businessList", JSON.stringify(this.businessList))
      });
    },
    getAuthorList() {
      this.loading = true;
      simpleList().then(response => {
        this.authorList = response.data;
        this.loading = false;
      });
    },
    getTagStyle(state) {
      const color = this.getTagClass(state);
      return {
        color: color,
        border: `1px solid ${color}`,
        borderRadius: '4px',
        fontSize: '12px',
        padding: '1px',
        lineHeight: '16px',
      };
    },
    getSimpleUserListByGroupId16() {
      this.loading = true;
      getSimpleUserListByGroupId16().then(response => {
        this.sysUserListByGroupId16 = response.data;
        this.loading = false;
        sessionStorage.setItem('sysUserListByGroupId16', JSON.stringify(this.sysUserListByGroupId16));
      });
    },
    getSupplierList() {
      this.loading = true;
      listByIsProtective().then(response => {
        this.supplierList = response.data;
        this.loading = false;
        sessionStorage.setItem('supplierList', JSON.stringify(this.supplierList));
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serial: null,
        name: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.telNumber = null,
        this.queryParams.myCreateTime = [],
        this.queryParams.myAuthtime = [],
        this.queryParams.myActivationTime = [],
        this.queryParams.mySuccessfutime = [],
        this.queryParams.myFailureTime = [],
        this.queryParams.firstChargePriceLow = null,
        this.queryParams.firstChargePriceUp = null,
        this.queryParams.labelTypes = [],
        this.queryParams.notLabelTypes = [],
        this.queryParams.types = [],
        this.queryParams.states = [],
        this.queryParams.doudianOrderStatuss = [],
        this.queryParams.classnames = [],
        this.queryParams.businessIds = [],
        this.queryParams.receiveOrderUserIds = [],
        this.queryParams.maintainManageIds = [],
        this.queryParams.doudianOrderAuthorIds = [],
        this.queryParams.doudianOrderManageAuthorIds = [],
        this.queryParams.manageIds = [],
        this.queryParams.suppliernames = [],
        this.queryParams.synthesize = null,
        this.queryParams.isActivations = [],
        this.queryParams.doudianOrderShopIds = null,
        this.queryParams.channelIds = [],
        this.queryParams.douDianGoodsNames = [],
        this.queryParams.evidenceChainTags = [],
        this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + ids + '"的数据项？').then(function () {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hmk/order/export', {
        ...this.queryParams
      }, `订单导出${formatTimeTitleExcel(new Date())}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>

.custom-button {
  padding: 2px 8px; /* 调整内边距 */
  font-size: 8px; /* 调整字体大小 */
}

::v-deep .el-table {
  .el-table__body {
    tr.highlight-row > td {
      background-color: #f0f9eb;
      // 可以添加其他高亮样式
      // font-weight: bold;
    }
  }
}

/* 修改已选中的标签文字颜色 */
::v-deep .el-select__tags .el-tag {
  color: #409EFF !important;
}


/* 如果需要修改背景色 */
::v-deep .el-select__tags .el-tag.el-tag--info {
  background-color: #f0f7ff !important;
  border-color: #d9ecff !important;
}

.other-icon {
  margin-left: 10px;
  color: #409EFF;
  cursor: pointer;
}


.hjfBottomFoot {
  display: flex;
  justify-content: end;
}

</style>
